<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <script type="text/javascript" src="https://lf6-cdn-tos.bytecdntp.com/cdn/expire-1-y/vue/2.6.14/vue.min.js"></script>
    <title>js撤销与回退操作</title>
    <style>
      li {
        color: #999;
      }
      .active {
        color: #252525;
      }
      .box {
        height: 460px;
        display: flex;
      }
    </style>
  </head>
  <body>
    <div id="app">
      <button @click="undo">撤销</button>
      <button @click="redo">重做</button>
      <hr />
      <div class="box">
        <textarea v-model="content" @input="inputChange" cols="50" rows="10"></textarea>
        <ol class="history_max">
          <li v-for="(e, i) in historyList" :key="e + i" :class="{ active: index >= i }">{{ e }}</li>
        </ol>
      </div>
    </div>

    <script>
      // 最大历史数量
      const maxStack = 20

      new Vue({
        el: '#app',
        data() {
          return {
            index: 0,
            content: '',
            historyList: []
          }
        },
        mounted() {
          this.historyList.push(this.content)
        },
        methods: {
          inputChange(e) {
            const value = e.target.value
            this.historyList.push(value)
            this.index = this.historyList.length - 1

            if (this.historyList.length > maxStack) {
              this.historyList.shift()
            }
          },
          undo() {
            if (this.index == 0) return console.info('没有撤销的了')
            this.content = this.historyList[--this.index]
          },
          redo() {
            if (this.index == this.historyList.length - 1) return console.info('没有重做的了')
            this.content = this.historyList[++this.index]
          }
        }
      })
    </script>
  </body>
</html>
